﻿using System.Text;
using System.Text.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Seer.SeerSocket;

public class ExplortStatisticBgService : BackgroundService
{
	private readonly SqliteDbContext ctx;
	private readonly ILogger<ExplortStatisticBgService> logger;
	private readonly IServiceScope serviceScope;
	private readonly SeerSocket seer;
	private readonly IDistributedCacheHelper helper;

	public ExplortStatisticBgService(IServiceScopeFactory scopeFactory)
	{
		this.serviceScope = scopeFactory.CreateScope();
		var sp = serviceScope.ServiceProvider;
		this.ctx = sp.GetRequiredService<SqliteDbContext>();
		this.logger = sp.GetRequiredService<ILogger<ExplortStatisticBgService>>();
		this.seer = sp.GetRequiredService<SeerSocket>();
		this.helper = sp.GetRequiredService<IDistributedCacheHelper>();
	}
	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	{
		while (!stoppingToken.IsCancellationRequested)
		{
			try
			{
				await DoExecuteAsync();
				await Task.Delay(2000);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "获取用户统计数据失败");
				await Task.Delay(1000);
			}
		}
	}

	private async Task DoExecuteAsync()
	{
		var msg = seer.Send(0x044c);
		await helper.UpdateAsync<string>("all1", async e => msg);

		// 文件路径
		// string filePath = @"F:\song\dotnet_seer_agv_timer\Db\all1.json";
		// 使用UTF-8编码写入文件
		// using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
		// {
		// 	using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
		// 	{
		// 		writer.Write(msg);
		// 	}
		// }

		// var users =  await this.ctx.Users.ToListAsync();
		// foreach(var user in users){
		// 	Console.WriteLine($"{DateTime.Now} : User : {user.NickName}");
		// 	break;
		// }


	}

	public override void Dispose()
	{
		base.Dispose();
		serviceScope.Dispose();
	}

}






